﻿using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace Assignment5
{
    // 客户实体类
    public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerId { get; private set; }

        [Required]
        [StringLength(100, ErrorMessage = "客户名称不能超过100个字符。")]
        public string CustomerName { get; private set; }

        // 构造函数，添加客户名称的验证
        public Customer(string customerName)
        {
            if (string.IsNullOrWhiteSpace(customerName))
                throw new ArgumentException("客户名称不能为空。", nameof(customerName));

            CustomerName = customerName;
        }

        // 重写 ToString 方法
        public override string ToString()
        {
            return $"客户姓名：{CustomerName}, 客户编号：{CustomerId}";
        }

        // 更新客户名称
        public void UpdateCustomerName(string newName)
        {
            if (string.IsNullOrWhiteSpace(newName))
                throw new ArgumentException("新客户名称不能为空。", nameof(newName));

            CustomerName = newName;
        }
    }

    // 客户管理类
    public class CustomerManager
    {
        private readonly MyDbContext _context;

        public CustomerManager(MyDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context), "DbContext 不能为空");
        }

        public void AddCustomer(Customer customer)
        {
            if (customer == null) throw new ArgumentNullException(nameof(customer), "客户不能为空");

            if (_context.Customers.Any(c => c.CustomerName == customer.CustomerName))
            {
                throw new InvalidOperationException("已存在同名客户。");
            }

            _context.Customers.Add(customer);
            _context.SaveChanges();
        }

        public void RemoveCustomer(int customerId)
        {
            // 通过客户ID查找客户，而不是通过Customer对象
            var customer = _context.Customers.Find(customerId);
            if (customer == null) throw new ArgumentNullException($"客户ID {customerId} 不存在");

            _context.Customers.Remove(customer);
            _context.SaveChanges();
        }
    }

    // 员工类，包含员工名称和ID
    public class Staff
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int StaffId { get; private set; }

        [Required]
        [StringLength(100, ErrorMessage = "员工姓名不能超过100个字符。")]
        public string StaffName { get; private set; }

        public Staff(string staffName)
        {
            if (string.IsNullOrWhiteSpace(staffName))
                throw new ArgumentException("员工姓名不能为空。", nameof(staffName));

            StaffName = staffName;
        }
    }
}